module ActionMailer
  class Base
    def create_mail_with_whitelist
      recipients whitelist_filter(recipients)
      cc         whitelist_filter(cc)
      bcc        whitelist_filter(bcc)
      create_mail_without_whitelist
    end
    alias_method_chain :create_mail, :whitelist

    def whitelist_filter(addresses)
      return nil unless addresses
      case addresses
      when String : email_whitelist.include?(addresses.downcase) ? addresses : nil
      when Array  : addresses.select{|address| whitelist_filter(address)}
      end
    end

    def email_whitelist
      @email_whitelist ||= EmailWhitelist::AllowedEmail.addresses.map(&:downcase)
    end
  end
end